//
//  HttpUtils.m
//  Weike
//
//  Created by leirz on 14-3-12.
//  Copyright (c) 2014年 winupon. All rights reserved.
//

#import "HttpRequest.h"
#import "AppUtils.h"
#import "DateUtil.h"
#import "Toast.h"
#import "EBNetWorkManager.h"
#import "NSDictionary+Ext.h"
#import "ServerMng.h"

#define HTTP_RESPONSE_STATUS_OK @"false"
#define HTTP_RESPONSE_STATUS_ERROR @"true"

#define HTTP_ERROR_CODE_TOKEN @"00012"  //token异常
#define HTTP_ERROR_CODE_KICK @"20029"   //账号被踢
#define HTTP_ERROR_CODE_UN_LOGIN @"20028"  //未登录，同00012
#define HTTP_ERROR_CODE_SINGKEY_LOST @"20026"   //密钥不存在，同00012
#define HTTP_ERROR_CODE_PARAM_ERROR @"00005"   //参数错误


@interface HttpRequest()
@end

@implementation HttpRequest

+ (HttpRequest *)sharedHttpRequest
{
    static HttpRequest *request = nil;
    static dispatch_once_t pred = 0;
    dispatch_once(&pred, ^{
        request = [[self alloc] init];
    });
    return request;
}

- (void)post:(NSString *)urlName params:(NSDictionary *)params complete:(void(^)(BOOL success, NSDictionary *result))complete
{
    [self sendRequest:urlName method:@"POST" params:params useCache:NO complete: complete showErrors:YES];
}

- (void)get:(NSString *)urlName params:(NSDictionary *)params complete:(void(^)(BOOL success, NSDictionary *result))complete
{
    [self sendRequest:urlName method:@"POST" params:params useCache:NO complete: complete showErrors:YES];
}

- (void)sendRequest:(NSString *)serviceName
             method:(NSString *)method
             params:(NSDictionary *)params1
           useCache:(BOOL)useCache
           complete:(void(^)(BOOL success, NSDictionary *result))complete
         showErrors:(BOOL)showErrors
{
    if(![AppUtils hasConnected:YES]){
        return;
    }
    NSLog(@"\nurl:%@\n%@\n",serviceName,params1);
    NSString *url = [self getRequestUrl:serviceName];
    if(params1 == nil){
        params1 = [NSMutableDictionary dictionary];
    }
    NSString *signKey = [self getSignInfo:params1];
    NSDictionary *requestparam = [[self getRequestParams:params1] copy];
    
    NSMutableURLRequest *request = [[EBNetWorkManager sharedKit] requestWithMethod:method URLString:url parameters:requestparam error:nil];
    // 设置请求超时时间(秒)
    NSUInteger timeout = [AppUtils toInteger:[params1 objectForKey:REQUEST_TIME_OUT]];
    timeout = timeout == 0 ? 30 : timeout;
    [request setTimeoutInterval:timeout];
    //设置固定的头部header信息-signkey
    [request setValue:signKey forHTTPHeaderField:@"X-JEECG-SIGN"];

    [[EBNetWorkManager sharedKit] taskWithRequest:request finished:^(NSData *data, NSURLResponse *response) {
        
        NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *responseObject = [AppUtils parseJSON:responseStr];
        NSLog(@"\n获取的接口数据是====%@",[AppUtils toJSONString:responseObject]);
        NSDictionary *resultDict = [NSDictionary changeType:responseObject];
        BOOL status = [AppUtils toString:resultDict[@"success"]].boolValue;
        if (status) {
            complete(YES, resultDict);
        } else {
            if([self handlerSuccess:resultDict]){
                complete(NO, resultDict);
            }
        }
    } failed:^(NSError *error) {
        NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
        [result setValue:@"无法请求服务器" forKey:@"message"];
        complete(NO, result);
        [self handlerError:error];
    }];
}

- (void)get:(NSString *)urlName arrayParams:(NSArray *)params complete:(void(^)(BOOL success, NSDictionary *result))complete
{
    [self sendRequest:urlName method:@"POST" arrayParams:params useCache:NO complete:complete showErrors:YES];
}

- (void)sendRequest:(NSString *)serviceName
             method:(NSString *)method
             arrayParams:(NSArray *)params1
           useCache:(BOOL)useCache
           complete:(void(^)(BOOL success, NSDictionary *result))complete
         showErrors:(BOOL)showErrors
{
    if(![AppUtils hasConnected:YES]){
        return;
    }
    if(params1 == nil){
        params1 = [NSMutableArray array];
    }
    NSLog(@"\nurl:%@\n%@\n",serviceName,params1);
    NSString *url = [self getRequestUrl:serviceName];
    NSString *signKey = [self getSignInfo:params1];
    NSDictionary *requestparam = [[self getRequestParams:params1] copy];
    
    NSMutableURLRequest *request = [[EBNetWorkManager sharedKit] requestWithMethod:method URLString:url parameters:requestparam error:nil];
    // 设置请求超时时间(秒)
    NSUInteger timeout =  30;
    [request setTimeoutInterval:timeout];
    //设置固定的头部header信息-signkey
    [request setValue:signKey forHTTPHeaderField:@"X-JEECG-SIGN"];
    
    [[EBNetWorkManager sharedKit] taskWithRequest:request finished:^(NSData *data, NSURLResponse *response) {
        
        NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *responseObject = [AppUtils parseJSON:responseStr];
        NSLog(@"\n获取的接口数据是====%@",[AppUtils toJSONString:responseObject]);
        NSDictionary *resultDict = [NSDictionary changeType:responseObject];
        BOOL status = [AppUtils toString:resultDict[@"success"]].boolValue;
        if (status) {
            complete(YES, resultDict);
        } else {
            if([self handlerSuccess:resultDict]){
                complete(NO, resultDict);
            }
        }
    } failed:^(NSError *error) {
        NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
        [result setValue:@"无法请求服务器" forKey:@"message"];
        complete(NO, result);
        [self handlerError:error];
    }];
}




- (NSMutableDictionary *)getRequestParams:(id)params
{
    NSMutableDictionary *requestParams = [[NSMutableDictionary alloc] init];
    [requestParams setValue:[AppUtils toJSONString:params] forKey:@"body"];
    return requestParams;
}

/**
 * 获取signkey
 */
- (NSString *)getSignInfo:(id)params
{
    NSMutableString *signStr = [NSMutableString string];
    [signStr appendString:[NSString stringWithFormat:@"body=%@&",[AppUtils toJSONString:params]]];

    [signStr appendString:[NSString stringWithFormat:@"key=%@",SIGN_KEY]];
    NSString * signKey = [AppUtils md5:[NSString stringWithFormat:@"%@",signStr]];
//    NSLog(@"签名串signKey= %@",signKey);
    return signKey;
}

- (NSString *)getRequestUrl:(NSString *)url
{
    if ([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]) {
        return url;
    }
    return [NSString stringWithFormat:@"%@%@", HTTP_DOMAIN, url];
}


- (BOOL) handlerSuccess:(NSDictionary *)result
{
//    NSString *errCode  =  result[@"error_code"];
//    if([errCode isEqualToString:HTTP_ERROR_CODE_TOKEN] ||
//       [errCode isEqualToString:HTTP_ERROR_CODE_UN_LOGIN] ||
//       [errCode isEqualToString:HTTP_ERROR_CODE_SINGKEY_LOST] ){
//        DSLog(@"errorMessage:%@", @"长时间未进行有效操作,请重新登录!");
//        [[LoginDataMng sharedInstance] reLogin:^(BOOL success) {
//        }];
//        return NO;
//    }else if([errCode isEqualToString:HTTP_ERROR_CODE_KICK]){
//        [Toast loaded];
//        DSLog(@"errorMessage:%@", @"您的账号在另一地点登录，您已被迫退出。如果不是您本人操作，您的密码可能已经泄露，建议您重新登录修改密码。");
//        [AppUtils showErrorAlertByKick];
//        return NO;
//    }else if([errCode isEqualToString:HTTP_ERROR_CODE_PARAM_ERROR]){
//        [Toast loaded];
//        DSLog(@"errorMessage:%@", result[@"message"]);
//        [AppUtils showErrorAlert:@"请求参数错误，请重新操作"];
//        return NO;
//    }
    NSString *message = result[@"message"];
    DSLog(@"errorMessage:%@", message);
    return YES;
}

- (void) handlerError:(NSError *)error
{
    DSLog(@"请求服务器数据出错：%@", error);
}



@end
